package org.jeecg.modules.flowable.service.action.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.jeecg.modules.flowable.common.util.IdUtil;
import org.jeecg.modules.flowable.common.util.validation.AssertValid;
import org.jeecg.modules.flowable.common.util.validation.MustParamValidation;
import org.jeecg.modules.flowable.dic.MatterFlowStatus;
import org.jeecg.modules.flowable.entity.TActMatterInstEntity;
import org.jeecg.modules.flowable.entity.TActTheendEntity;
import org.jeecg.modules.flowable.mapper.TActMatterInstMapper;
import org.jeecg.modules.flowable.mapper.TActTheendMapper;
import org.jeecg.modules.flowable.service.FlowProcService;
import org.jeecg.modules.flowable.service.FlowableService;
import org.jeecg.modules.flowable.service.action.ActionBody;
import org.jeecg.modules.flowable.service.action.ActionExec;
import org.jeecg.modules.flowable.system.core.SystemUser;
import org.jeecg.modules.flowable.system.etc.SystemUserUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Title: 流程继续  <br>
 * Desc:  <br>
 * Date: 6/26/22 10:01 AM <br>
 * Company: 联通（辽宁）产业互联网有限公司 <br>
 *
 * @author zxd
 * @version 1.0.0
 */
@Service("Submit")
@Slf4j
public class Submit implements ActionExec {
    @Autowired
    private FlowProcService flowProcService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TActTheendMapper tActTheendMapper;

    @Autowired
    private TActMatterInstMapper tActMatterInstMapper;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deal(ActionBody argActionBody, String argActionFunname, String argActionFuncode) {
        MustParamValidation.mustValidation(argActionBody.getMatterInstId(), argActionBody.getTaskId());
        SystemUser loginUser = SystemUserUtil.getSystemUser();
        DateTime now = DateTime.now();
        // 第一步：保存
        flowProcService.save(argActionBody.getMatterInstId(), argActionBody.getTaskId(), argActionBody.getAttType(), argActionBody.getAttDesc(), argActionBody.getFormData(), argActionBody.getAttrList(), argActionFunname, argActionFuncode, argActionBody.getFormContent());
        // 第二步：流程处理
        // 认领任务
        taskService.claim(argActionBody.getTaskId(), loginUser.getId());
        // 完成流程
        String formContent = argActionBody.getFormContent();
        if (AssertValid.isNotEmpty(formContent)){
            Map<String,Object> formContentMap =  JSONObject.parseObject(formContent).getInnerMap();
            log.info("Biz form data: {}", formContentMap);
            taskService.complete(argActionBody.getTaskId(), formContentMap);
        } else{
            taskService.complete(argActionBody.getTaskId());
        }
        // if (AssertValid.isNotEmpty(argActionBody.getFormData()))
        // taskService.complete(argActionBody.getTaskId(), argActionBody.getFormData());
        // else
        // taskService.complete(argActionBody.getTaskId());
        log.info("流程提交成功");
        // 判断流程是否结束，如果流程结束，回写流程结果表
        TActMatterInstEntity matterinstEn = tActMatterInstMapper.selectById(argActionBody.getMatterInstId());
        Boolean flowFinish = flowableService.isFlowFinish(matterinstEn.getProcInstId());
        if (flowFinish) {
            TActTheendEntity tActTheendEntity = new TActTheendEntity().setId(IdUtil.getStringId()).setCreateBy(loginUser.getRealname()).setCreateTime(now.toDate()).setUpdateBy(loginUser.getRealname()).setUpdateTime(now.toDate()).setDelFlag(0);
            ;
            tActTheendEntity.setAcceptId(loginUser.getId());
            tActTheendEntity.setAcceptName(loginUser.getRealname());
            tActTheendEntity.setEndTime(now.toDate());
            tActTheendEntity.setLastAttType(argActionBody.getAttType());
            tActTheendEntity.setProcInstId(matterinstEn.getProcInstId());
            tActTheendEntity.setTaskId(argActionBody.getTaskId());
            tActTheendMapper.insert(tActTheendEntity);

            // 回写事项实例表
            LambdaQueryWrapper<TActMatterInstEntity> qq = new LambdaQueryWrapper<>();
            qq.eq(TActMatterInstEntity::getId, argActionBody.getMatterInstId());
            TActMatterInstEntity inst = tActMatterInstMapper.selectList(qq).get(0);
            TActMatterInstEntity tActMatterInstEntity = new TActMatterInstEntity();
            tActMatterInstEntity.setEndTime(now.toDate());
            tActMatterInstEntity.setStatus(MatterFlowStatus.FINISH);
            tActMatterInstEntity.setCostTime(now.toDate().getTime() - inst.getStartTime().getTime());
            tActMatterInstMapper.update(tActMatterInstEntity, qq);
        }
        return true;
    }
}